<!DOCTYPE html>
<html lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">

    <!--[if lt IE 9]>
        <style>body {display: none; background: none !important} </style>
        <meta http-equiv="Refresh" Content="0; url=//outdatedbrowser.com/" />
    <![endif]-->

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta name="format-detection" content="telephone=no">
<meta name="author" content="Ren ZM">



<meta name="description" content="在web1中，创建了一个完全后端掌控的动态网站，可是写html那么难，还要在后端代码里去渲染它，着实麻烦。这里如果后端服务器只提供数据操作能力，前端用于展示数据和请求服务器处理数据，这岂不是天下太平。">
<meta name="keywords" content="note,Nodejs">
<meta property="og:type" content="article">
<meta property="og:title" content="web2.简单网站的前后端分离">
<meta property="og:url" content="https://littlepro.gitee.io/mytpages/2019/09/29/web2-简单网站的前后端分离/index.html">
<meta property="og:site_name" content="Xbiubiubiu">
<meta property="og:description" content="在web1中，创建了一个完全后端掌控的动态网站，可是写html那么难，还要在后端代码里去渲染它，着实麻烦。这里如果后端服务器只提供数据操作能力，前端用于展示数据和请求服务器处理数据，这岂不是天下太平。">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-10-22T13:22:48.658Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="web2.简单网站的前后端分离">
<meta name="twitter:description" content="在web1中，创建了一个完全后端掌控的动态网站，可是写html那么难，还要在后端代码里去渲染它，着实麻烦。这里如果后端服务器只提供数据操作能力，前端用于展示数据和请求服务器处理数据，这岂不是天下太平。">

<link rel="apple-touch-icon" href="/mytpages//apple-touch-icon.png">


    <link rel="alternate" href="/atom.xml" title="Xbiubiubiu" type="application/atom+xml">



    <link rel="shortcut icon" href="/mytpages//favicon.png">



    <link href="//cdn.bootcss.com/animate.css/3.5.1/animate.min.css" rel="stylesheet">



    <link href="//cdn.bootcss.com/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet">



    <script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
    <link href="//cdn.bootcss.com/pace/1.0.2/themes/blue/pace-theme-minimal.css" rel="stylesheet">


<link rel="stylesheet" href="/mytpages/css/style.css">



<link href="//cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">


<title>web2.简单网站的前后端分离 | Xbiubiubiu</title>

<script src="//cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>

<script>
    var yiliaConfig = {
        fancybox: true,
        animate: true,
        isHome: false,
        isPost: true,
        isArchive: false,
        isTag: false,
        isCategory: false,
        fancybox_js: "//cdn.bootcss.com/fancybox/2.1.5/jquery.fancybox.min.js",
        scrollreveal: "//cdn.bootcss.com/scrollReveal.js/3.1.4/scrollreveal.min.js",
        search: false
    }
</script>


    <script> yiliaConfig.jquery_ui = [false]; </script>



    <script> yiliaConfig.rootUrl = /mytpages/; </script>







    <script src="/mytpages/live2d-widget/autoload.js"></script>


</head></html>
<body>
  <div id="container">
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
    <header id="header" class="inner">
        <a href="/mytpages/" class="profilepic">
            <img src="/mytpages//img/avatar.png" class="animated zoomIn">
        </a>
        <hgroup>
          <h1 class="header-author"><a href="/mytpages/">Ren ZM</a></h1>
        </hgroup>

        
        <p class="header-subtitle">--ロリは正義</p>
        

        


        
            <div id="switch-btn" class="switch-btn">
                <div class="icon">
                    <div class="icon-ctn">
                        <div class="icon-wrap icon-house" data-idx="0">
                            <div class="birdhouse"></div>
                            <div class="birdhouse_holes"></div>
                        </div>
                        <div class="icon-wrap icon-ribbon hide" data-idx="1">
                            <div class="ribbon"></div>
                        </div>
                        
                        <div class="icon-wrap icon-link hide" data-idx="2">
                            <div class="loopback_l"></div>
                            <div class="loopback_r"></div>
                        </div>
                        
                        
                        <div class="icon-wrap icon-me hide" data-idx="3">
                            <div class="user"></div>
                            <div class="shoulder"></div>
                        </div>
                        
                    </div>
                    
                </div>
                <div class="tips-box hide">
                    <div class="tips-arrow"></div>
                    <ul class="tips-inner">
                        <li>菜单</li>
                        <li>标签</li>
                        
                        <li>友情链接</li>
                        
                        
                        <li>关于我</li>
                        
                    </ul>
                </div>
            </div>
        

        <div id="switch-area" class="switch-area">
            <div class="switch-wrap">
                <section class="switch-part switch-part1">
                    <nav class="header-menu">
                        <ul>
                        
                            <li><a href="/mytpages//mytpages/../">主页</a></li>
                        
                            <li><a href="/mytpages//mytpages/../archives/">所有文章</a></li>
                        
                            <li><a href="/mytpages//mytpages/../tags/">标签云</a></li>
                        
                            <li><a href="/mytpages//mytpages/../about/">关于我</a></li>
                        
                        </ul>
                    </nav>
                    <nav class="header-nav">
                        <ul class="social">
                            
                                <a class="fa Email" href="mailto:784709355@qq.com" title="Email"></a>
                            
                                <a class="fa GitHub" href="https://github.com/rzzz" title="GitHub"></a>
                            
                                <a class="fa Gitee" href="https://gitee.com/littlepro" title="Gitee"></a>
                            
                                <a class="fa V2EX" href="/mytpages/" title="V2EX"></a>
                            
                                <a class="fa 知乎" href="/mytpages/" title="知乎"></a>
                            
                                <a class="fa 网易云音乐" href="/mytpages/" title="网易云音乐"></a>
                            
                                <a class="fa bilibili" href="/mytpages/" title="bilibili"></a>
                            
                        </ul>
                    </nav>
                </section>
                
                
                <section class="switch-part switch-part2">
                    <div class="widget tagcloud" id="js-tagcloud">
                        <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/mytpages/tags/JavaScript/">JavaScript</a></li><li class="tag-list-item"><a class="tag-list-link" href="/mytpages/tags/MySql/">MySql</a></li><li class="tag-list-item"><a class="tag-list-link" href="/mytpages/tags/NodeJS/">NodeJS</a></li><li class="tag-list-item"><a class="tag-list-link" href="/mytpages/tags/Nodejs/">Nodejs</a></li><li class="tag-list-item"><a class="tag-list-link" href="/mytpages/tags/PS3/">PS3</a></li><li class="tag-list-item"><a class="tag-list-link" href="/mytpages/tags/c/">c</a></li><li class="tag-list-item"><a class="tag-list-link" href="/mytpages/tags/c/">c++</a></li><li class="tag-list-item"><a class="tag-list-link" href="/mytpages/tags/cocos2dx/">cocos2dx</a></li><li class="tag-list-item"><a class="tag-list-link" href="/mytpages/tags/markdown/">markdown</a></li><li class="tag-list-item"><a class="tag-list-link" href="/mytpages/tags/note/">note</a></li><li class="tag-list-item"><a class="tag-list-link" href="/mytpages/tags/sort/">sort</a></li><li class="tag-list-item"><a class="tag-list-link" href="/mytpages/tags/test/">test</a></li><li class="tag-list-item"><a class="tag-list-link" href="/mytpages/tags/tool/">tool</a></li><li class="tag-list-item"><a class="tag-list-link" href="/mytpages/tags/usage/">usage</a></li></ul>
                    </div>
                </section>
                
                
                
                <section class="switch-part switch-part3">
                    <div id="js-friends">
                    
                      <a class="main-nav-link switch-friends-link" href="https://hexo.io">Hexo</a>
                    
                      <a class="main-nav-link switch-friends-link" href="https://pages.github.com/">GitHub</a>
                    
                      <a class="main-nav-link switch-friends-link" href="http://moxfive.xyz/">MOxFIVE</a>
                    
                    </div>
                </section>
                

                
                
                <section class="switch-part switch-part4">
                
                    <div id="js-aboutme">ロリは正義</div>
                </section>
                
            </div>
        </div>
    </header>                
</div>
    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
      <div class="overlay">
          <div class="slider-trigger"></div>
          <h1 class="header-author js-mobile-header hide"><a href="/" title="回到主页">Ren ZM</a></h1>
      </div>
    <div class="intrude-less">
        <header id="header" class="inner">
            <a href="/mytpages/" class="profilepic">
                <img src="/mytpages//img/avatar.png" class="animated zoomIn">
            </a>
            <hgroup>
              <h1 class="header-author"><a href="/mytpages/" title="回到主页">Ren ZM</a></h1>
            </hgroup>
            
            <p class="header-subtitle">--ロリは正義</p>
            
            <nav class="header-menu">
                <ul>
                
                    <li><a href="/mytpages/../">主页</a></li>
                
                    <li><a href="/mytpages/../archives/">所有文章</a></li>
                
                    <li><a href="/mytpages/../tags/">标签云</a></li>
                
                    <li><a href="/mytpages/../about/">关于我</a></li>
                
                <div class="clearfix"></div>
                </ul>
            </nav>
            <nav class="header-nav">
                        <ul class="social">
                            
                                <a class="fa Email" target="_blank" href="mailto:784709355@qq.com" title="Email"></a>
                            
                                <a class="fa GitHub" target="_blank" href="https://github.com/rzzz" title="GitHub"></a>
                            
                                <a class="fa Gitee" target="_blank" href="https://gitee.com/littlepro" title="Gitee"></a>
                            
                                <a class="fa V2EX" target="_blank" href="/mytpages/" title="V2EX"></a>
                            
                                <a class="fa 知乎" target="_blank" href="/mytpages/" title="知乎"></a>
                            
                                <a class="fa 网易云音乐" target="_blank" href="/mytpages/" title="网易云音乐"></a>
                            
                                <a class="fa bilibili" target="_blank" href="/mytpages/" title="bilibili"></a>
                            
                        </ul>
            </nav>
        </header>                
    </div>
    <link class="menu-list" tags="标签" friends="友情链接" about="关于我"/>
</nav>
      <div class="body-wrap"><article id="post-web2-简单网站的前后端分离" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="/mytpages/2019/09/29/web2-简单网站的前后端分离/" class="article-date">
      <time datetime="2019-09-29T09:15:13.000Z" itemprop="datePublished">2019-09-29</time>
</a>


    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      web2.简单网站的前后端分离
    </h1>
  

      </header>
      
      <div class="article-info article-info-post">
        
    <div class="article-category tagcloud">
    <a class="article-category-link" href="/mytpages/categories/web-test/">web-test</a>
    </div>


        
    <div class="article-tag tagcloud">
        <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/mytpages/tags/Nodejs/">Nodejs</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/mytpages/tags/note/">note</a></li></ul>
    </div>

        <div class="clearfix"></div>
      </div>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
        <p>在web1中，创建了一个完全后端掌控的动态网站，可是写html那么难，还要在后端代码里去渲染它，着实麻烦。<br>这里如果后端服务器只提供数据操作能力，前端用于展示数据和请求服务器处理数据，这岂不是天下太平。</p>
<a id="more"></a>

<h3 id="REST风格"><a href="#REST风格" class="headerlink" title="REST风格"></a>REST风格</h3><p>编写REST API，实际上就是编写处理HTTP请求的async函数，不过，REST请求和普通的HTTP请求有几个特殊的地方：</p>
<ul>
<li>REST请求仍然是标准的HTTP请求，但是，除了GET请求外，POST、PUT等请求的body是JSON数据格式，请求的Content-Type为application/json；</li>
<li>REST响应返回的结果是JSON数据格式，因此，响应的Content-Type也是application/json。</li>
</ul>
<h3 id="增加几个webAPI"><a href="#增加几个webAPI" class="headerlink" title="增加几个webAPI"></a>增加几个webAPI</h3><p>先不说前后端分离的事，先给网站增加几个api，使用rest风格。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">router.get(<span class="string">'/api/getmsgs'</span>, <span class="keyword">async</span> (ctx, next) =&gt; &#123;</span><br><span class="line">    <span class="keyword">let</span> rows = <span class="keyword">await</span> db.curd(<span class="string">'SELECT * FROM msgs'</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(rows);</span><br><span class="line">    <span class="keyword">let</span> msgs = [];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; rows.length; i++)&#123;</span><br><span class="line">        msgs.push(<span class="built_in">JSON</span>.stringify(rows[i]));</span><br><span class="line">    &#125;</span><br><span class="line">    ctx.response.type = <span class="string">'application/json'</span>;</span><br><span class="line">    ctx.response.body = &#123;</span><br><span class="line">        ok: <span class="number">1</span>,</span><br><span class="line">        msgs</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;);</span><br><span class="line">router.post(<span class="string">'/api/addmsg'</span>, <span class="keyword">async</span> (ctx, next) =&gt; &#123;</span><br><span class="line">    <span class="keyword">var</span> msg = ctx.request.body.msg || <span class="string">''</span>;</span><br><span class="line">    ctx.response.type = <span class="string">'application/json'</span>;</span><br><span class="line">    <span class="keyword">if</span> (msg) &#123;</span><br><span class="line">        <span class="keyword">let</span> rows = <span class="keyword">await</span> db.curd(<span class="string">'INSERT INTO msgs(msg) VALUES(?)'</span>, [msg]);</span><br><span class="line">        <span class="built_in">console</span>.log(rows);<span class="comment">// OkPacket</span></span><br><span class="line">        ctx.response.body = &#123;</span><br><span class="line">            ok: <span class="number">1</span></span><br><span class="line">        &#125;;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        ctx.response.body = &#123;</span><br><span class="line">            ok: <span class="number">0</span>,</span><br><span class="line">            code: <span class="number">10001</span></span><br><span class="line">        &#125;;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>浏览器中测试第一条很方便就能得到结果，至于第二条，要向api地址post数据，接下来再看。</p>
<h3 id="在自己的网站中使用自己的webAPI"><a href="#在自己的网站中使用自己的webAPI" class="headerlink" title="在自己的网站中使用自己的webAPI"></a>在自己的网站中使用自己的webAPI</h3><p>先在router里新增一个url，直接返回一个html，然后在html里使用ajax来与上面创建的api接口进行数据操作</p>
<p>koa新增</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">router.get(<span class="string">'/msg/list'</span>, <span class="keyword">async</span> (ctx, next) =&gt; &#123;</span><br><span class="line">    ctx.response.body = env.render(<span class="string">'msg/list.html'</span>, &#123;&#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>新增msg/list.html文件</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"msg"</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"addmsg"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">form</span> <span class="attr">id</span>=<span class="string">"form1"</span> <span class="attr">onsubmit</span>=<span class="string">"return false"</span> <span class="attr">action</span>=<span class="string">"##"</span> <span class="attr">method</span>=<span class="string">"post"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">p</span>&gt;</span>msg: <span class="tag">&lt;<span class="name">input</span> <span class="attr">name</span>=<span class="string">"msg"</span> <span class="attr">value</span>=<span class="string">"test"</span>&gt;</span><span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">p</span>&gt;</span><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"submit"</span> <span class="attr">value</span>=<span class="string">"Submit"</span> <span class="attr">id</span>=<span class="string">"msgpost"</span>&gt;</span><span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">form</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">    $(<span class="built_in">document</span>).ready(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">        $.getJSON(<span class="string">"/api/getmsgs"</span>, <span class="function"><span class="keyword">function</span> (<span class="params">result</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">            <span class="keyword">if</span> (result.ok) &#123;</span></span><br><span class="line"><span class="javascript">                <span class="keyword">var</span> str = <span class="string">""</span>;</span></span><br><span class="line"><span class="javascript">                <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; result.msgs.length; i++) &#123;</span></span><br><span class="line"><span class="javascript">                    str += <span class="string">"&lt;p&gt;"</span> + i + <span class="string">"--:"</span> + result.msgs[i] + <span class="string">"&lt;/p&gt;"</span>;</span></span><br><span class="line">                &#125;</span><br><span class="line"><span class="javascript">                $(<span class="string">"#msg"</span>).append(str);</span></span><br><span class="line"><span class="javascript">            &#125; <span class="keyword">else</span> &#123;</span></span><br><span class="line"><span class="javascript">                $(<span class="string">"#msg"</span>).text(<span class="string">"get error"</span>);</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line"><span class="javascript">        $(<span class="string">"#msgpost"</span>).click(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">            $.post(<span class="string">"/api/addmsg"</span>, $(<span class="string">"#form1"</span>).serialize(), <span class="function"><span class="keyword">function</span> (<span class="params">result</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">                alert(<span class="built_in">JSON</span>.stringify(result));</span></span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;);</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="把前后端分开"><a href="#把前后端分开" class="headerlink" title="把前后端分开"></a>把前后端分开</h3><p>上面建立的koa，现在只用来书写rest风格的api，只用于处理前端的http请求，操作数据库，然后返回json格式的http响应。<br>那么现在为它单独新开一个koa-app服务器，只提供api，这样的话，前端可以是任何设备，浏览器，桌面客户端，移动应用等。<br>后端代码就先这样，现在创建前端web服务器。</p>
<p>这里可以使用现成的web服务器，不过这里选择用express来建立一个web服务器，但是不使用它的后端路由功能，仅仅用它的静态文件托管。</p>
<p>1.npm init, npm install express，无需express-generator</p>
<p>2.app.js</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> express = <span class="built_in">require</span>(<span class="string">'express'</span>);</span><br><span class="line"><span class="keyword">const</span> app = express();</span><br><span class="line">app.get(<span class="string">'/'</span>, (req, res) =&gt; &#123;</span><br><span class="line">    res.send(<span class="string">'Hello World!'</span>);</span><br><span class="line">&#125;);</span><br><span class="line">app.listen(<span class="number">4000</span>, () =&gt; <span class="built_in">console</span>.log(<span class="string">'Example app listening on port 4000!'</span>))</span><br></pre></td></tr></table></figure>

<p>以上代码测试通过，能路由到根。</p>
<p>3.托管静态文件</p>
<p>新增几个文件</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">-public/</span><br><span class="line">  index.html</span><br><span class="line">  test/</span><br><span class="line">    index.html</span><br></pre></td></tr></table></figure>

<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 对根托管静态文件</span></span><br><span class="line">app.use(express.static(<span class="string">'public'</span>))</span><br><span class="line"><span class="comment">// 会被public/index.html阻挡</span></span><br><span class="line">app.get(<span class="string">'/'</span>, (req, res) =&gt; &#123;</span><br><span class="line">    res.send(<span class="string">'Hello World!'</span>);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// 会被public/test/index.html阻挡</span></span><br><span class="line">app.get(<span class="string">'/test'</span>, (req, res) =&gt; &#123;</span><br><span class="line">    res.send(<span class="string">'Hello test!'</span>);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// 可达</span></span><br><span class="line">app.get(<span class="string">'/test2'</span>, (req, res) =&gt; &#123;</span><br><span class="line">    res.send(<span class="string">'Hello test2!'</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>4.在这个服务器里去请求上面的koa2-api服务器</p>
<p>仅仅把koa2的msg/list.html拷贝过来，然后修改以下地方</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$.getJSON("http://192.168.0.121:3000/api/getmsgs", function (result) &#123;...&#125;);</span><br><span class="line">$.post("http://192.168.0.121:3000/api/addmsg", $("#form1").serialize(), function (result) &#123;...&#125;);</span><br></pre></td></tr></table></figure>

<p>这里会发生跨域问题，这里有几种修改方式：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1.服务端允许cors</span></span><br><span class="line">    app.use(cors());</span><br><span class="line"></span><br><span class="line"><span class="comment">//2.使用jsonp，借助于script标签的src因为属于html标签，依然支持跨域访问</span></span><br><span class="line">    <span class="comment">// 前端</span></span><br><span class="line">    $(<span class="string">"#jsonp"</span>).click(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">        $.ajax(&#123;</span><br><span class="line">            url: <span class="string">"http://192.168.0.121:3000/api/jsonp/getmsgs"</span>,</span><br><span class="line">            dataType: <span class="string">"jsonp"</span>,</span><br><span class="line">            jsonp: <span class="string">"callback"</span></span><br><span class="line">        &#125;).done(<span class="function">(<span class="params">data</span>)=&gt;</span>&#123;</span><br><span class="line">            alert(<span class="built_in">JSON</span>.stringify(data));</span><br><span class="line">        &#125;).fail(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">            alert(<span class="string">"jsonp fail"</span>);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="comment">// 后端</span></span><br><span class="line">    router.get(<span class="string">'/api/jsonp/getmsgs'</span>, <span class="keyword">async</span> (ctx, next) =&gt; &#123;</span><br><span class="line">        <span class="comment">// 获取jsonp的callback</span></span><br><span class="line">        <span class="keyword">let</span> callbackName = ctx.request.query.callback || <span class="string">'callback'</span>;</span><br><span class="line">        <span class="keyword">let</span> returnData = &#123;</span><br><span class="line">            success: <span class="literal">true</span>,</span><br><span class="line">            data: &#123;</span><br><span class="line">                text: <span class="string">'this is a jsonp api'</span>,</span><br><span class="line">                time: <span class="keyword">new</span> <span class="built_in">Date</span>().getTime(),</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">// jsonp的script字符串</span></span><br><span class="line">        <span class="keyword">let</span> jsonpStr = <span class="string">`;<span class="subst">$&#123;callbackName&#125;</span>(<span class="subst">$&#123;<span class="built_in">JSON</span>.stringify(returnData)&#125;</span>)`</span>;</span><br><span class="line">        <span class="comment">// 用text/javascript，让请求支持跨域获取</span></span><br><span class="line">        ctx.response.type = <span class="string">'text/javascript'</span>;</span><br><span class="line">        <span class="comment">// 输出jsonp字符串</span></span><br><span class="line">        ctx.response.body = jsonpStr;</span><br><span class="line">    &#125;);</span><br></pre></td></tr></table></figure>

<h3 id="阶段性总结"><a href="#阶段性总结" class="headerlink" title="阶段性总结"></a>阶段性总结</h3><p>这里基本上，将前端展示页面，放在单独的web服务器上，内部使用ajxa去与后端服务器交换数据，<br>后端服务器基本上只需要处理好自己的业务逻辑，对外提供api，<br>前端可以使用更多的前端框架来书写html展示，ajax请求。</p>

      
    </div>
    
  </div>
  
    


    <nav id="article-nav">
        
            <div id="article-nav-newer" class="article-nav-title">
                <a href="/mytpages/2019/10/09/web3-单页Web应用/">
                    web3.单页Web应用
                </a>
            </div>
        
        
            <div id="article-nav-older" class="article-nav-title">
                <a href="/mytpages/2019/09/29/web1-创建一个简单的网站/">
                    web1.创建一个简单的网站
                </a>
            </div>
        
    </nav>

  
</article>

    <div id="toc" class="toc-article">
        <strong class="toc-title">文章目录</strong>
        
            <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#REST风格"><span class="toc-number">1.</span> <span class="toc-text">REST风格</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#增加几个webAPI"><span class="toc-number">2.</span> <span class="toc-text">增加几个webAPI</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#在自己的网站中使用自己的webAPI"><span class="toc-number">3.</span> <span class="toc-text">在自己的网站中使用自己的webAPI</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#把前后端分开"><span class="toc-number">4.</span> <span class="toc-text">把前后端分开</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#阶段性总结"><span class="toc-number">5.</span> <span class="toc-text">阶段性总结</span></a></li></ol>
        
    </div>
    <style>
        .left-col .switch-btn,
        .left-col .switch-area {
            display: none;
        }
        .toc-level-3 i,
        .toc-level-3 ol {
            display: none !important;
        }
    </style>

    <input type="button" id="tocButton" value="隐藏目录"  title="点击按钮隐藏或者显示文章目录">

    <script>
        yiliaConfig.toc = ["隐藏目录", "显示目录", !!"false"];
    </script>



    
<div class="share">
    
        <div class="bdsharebuttonbox">
            <a href="#" class="fa fa-twitter bds_twi" data-cmd="twi" title="分享到推特"></a>
            <a href="#" class="fa fa-weibo bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
            <a href="#" class="fa fa-qq bds_sqq" data-cmd="sqq" title="分享给 QQ 好友"></a>
            <a href="#" class="fa fa-files-o bds_copy" data-cmd="copy" title="复制网址"></a>
            <a href="#" class="fa fa fa-envelope-o bds_mail" data-cmd="mail" title="通过邮件分享"></a>
            <a href="#" class="fa fa-weixin bds_weixin" data-cmd="weixin" title="生成文章二维码"></a>
            <a href="#" class="fa fa-share-alt bds_more" data-cmd="more"></i></a>
        </div>
        <script>
            window._bd_share_config={
                "common":{"bdSnsKey":{},"bdText":"web2.简单网站的前后端分离　| Xbiubiubiu　","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"24"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
        </script>
    

    
</div>







    




    <div class="scroll" id="post-nav-button">
        
            <a href="/mytpages/2019/10/09/web3-单页Web应用/" title="上一篇: web3.单页Web应用">
                <i class="fa fa-angle-left"></i>
            </a>
        

        <a title="文章列表"><i class="fa fa-bars"></i><i class="fa fa-times"></i></a>

        
            <a href="/mytpages/2019/09/29/web1-创建一个简单的网站/" title="下一篇: web1.创建一个简单的网站">
                <i class="fa fa-angle-right"></i>
            </a>
        
    </div>

    <ul class="post-list"><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/12/13/cpp：allocator-new/">cpp：allocator,new</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/11/28/CPP标准库-note/">CPP标准库-note</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/11/27/C与win32API/">C与win32API</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/11/27/C标准库-note/">C标准库</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/11/26/cpp的lib和dll/">cpp的lib和dll</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/11/25/编译cpp-vs2015/">编译cpp-vs2015</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/11/23/编译cpp-准备/">编译c++准备</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/11/18/simple-opengl/">simple opengl</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/11/15/cocos2dx-action/">cocos2dx-action</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/11/15/cocos2dx-schedule/">cocos2dx-schedule</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/11/14/cocos2dx在win32上写日志文件/">cocos2dx在win32上写日志文件</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/11/14/cocos2dx在win32上播放ogg/">cocos2dx在win32上播放ogg</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/11/14/cocos2dx字库缺失文字处理/">cocos2dx字库缺失文字处理</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/11/14/cocos2dx工作目录修改/">cocos2dx工作目录修改</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/11/13/cocos2dx-android/">cocos2dx-android</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/11/12/cocos2dx-win32/">cocos2dx-win32</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/11/11/Sublimer-Text/">Sublimer Text</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/11/07/潜意识？？设计模式/">潜意识？？设计模式</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/11/04/BST？AVL？红黑树？/">BST？AVL？红黑树？</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/11/01/几种排序算法示例代码/">几种排序算法示例代码</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/10/31/引子-基础算法？？/">引子-基础算法？？</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/10/31/引子-数据结构？？/">引子-数据结构？？</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/10/25/不会懂分布式系统的/">不会懂分布式系统的</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/10/24/MySql简单使用-adv/">MySql简单使用-adv</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/10/24/MySql简单使用/">MySql简单使用</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/10/18/PS3-HEN破相关记录/">PS3-HEN破相关记录</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/10/09/测试使用云函数扩展码云page/">测试使用云函数扩展码云page</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/10/09/web3-单页Web应用/">web3.单页Web应用</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/09/29/web2-简单网站的前后端分离/">web2.简单网站的前后端分离</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/09/29/web1-创建一个简单的网站/">web1.创建一个简单的网站</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/09/27/NodeJS-简单使用/">NodeJS 简单使用</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/09/27/JavaScript-other/">JavaScript-other</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/09/27/JavaScript-模块/">JavaScript-模块</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/09/27/JavaScript-简单使用/">JavaScript 简单使用</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/09/27/github-gitee-chrome文件树插件/">github & gitee chrome文件树插件</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/09/26/markdown-简单使用/">markdown 简单使用示例</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/09/25/hello-world/">Hello World</a></li><li class="post-list-item"><a class="post-list-link" href="/mytpages/2019/09/24/zzTest-article0/">zzTest article0</a></li></ul>




    <script>
        
    </script>
</div>
      <footer id="footer">
    <div class="outer">
        <div id="footer-info">
            <div class="footer-left">
                <i class="fa fa-copyright"></i> 
                2019-2020 Ren ZM
            </div>
            <div class="footer-right">
                <a href="http://hexo.io/" target="_blank" title="快速、简洁且高效的博客框架">Hexo</a>  Theme <a href="https://github.com/MOxFIVE/hexo-theme-yelee" target="_blank" title="简而不减 Hexo 双栏博客主题  v3.5">Yelee</a> by MOxFIVE <i class="fa fa-heart animated infinite pulse"></i>
            </div>
        </div>
        
            <div class="visit">
                
                    <span id="busuanzi_container_site_pv" style='display:none'>
                        <span id="site-visit" title="本站到访数"><i class="fa fa-user" aria-hidden="true"></i><span id="busuanzi_value_site_uv"></span>
                        </span>
                    </span>
                
                
                    <span>| </span>
                
                
                    <span id="busuanzi_container_page_pv" style='display:none'>
                        <span id="page-visit"  title="本页阅读量"><i class="fa fa-eye animated infinite pulse" aria-hidden="true"></i><span id="busuanzi_value_page_pv"></span>
                        </span>
                    </span>
                
            </div>
        
    </div>
</footer>
    </div>
    
<script data-main="/mytpages/js/main.js" src="//cdn.bootcss.com/require.js/2.2.0/require.min.js"></script>

    <script>
        $(document).ready(function() {
            var iPad = window.navigator.userAgent.indexOf('iPad');
            if (iPad > -1 || $(".left-col").css("display") === "none") {
                var bgColorList = ["#9db3f4", "#414141", "#e5a859", "#f5dfc6", "#c084a0", "#847e72", "#cd8390", "#996731"];
                var bgColor = Math.ceil(Math.random() * (bgColorList.length - 1));
                $("body").css({"background-color": bgColorList[bgColor], "background-size": "cover"});
            }
            else {
                var backgroundnum = 5;
                var backgroundimg = "url(/mytpages//background/bg-x.jpg)".replace(/x/gi, Math.ceil(Math.random() * backgroundnum));
                $("body").css({"background": backgroundimg, "background-attachment": "fixed", "background-size": "cover"});
            }
        })
    </script>





<div class="scroll" id="scroll">
    <a href="#" title="返回顶部"><i class="fa fa-arrow-up"></i></a>
    <a href="#comments" onclick="load$hide();" title="查看评论"><i class="fa fa-comments-o"></i></a>
    <a href="#footer" title="转到底部"><i class="fa fa-arrow-down"></i></a>
</div>
<script>
    // Open in New Window
    
        var oOpenInNew = {
            
            
            
            
            
            
             archives: ".archive-article-title", 
             miniArchives: "a.post-list-link", 
            
             friends: "#js-friends a", 
             socail: ".social a" 
        }
        for (var x in oOpenInNew) {
            $(oOpenInNew[x]).attr("target", "_blank");
        }
    
</script>

<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
  </div>
</body>
</html>